using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using SuperMarketManagement.DAO.NHibernate;
using SuperMarketManagement.Entity;

namespace SuperMarketManagement.Web.Controllers
{
    [Authorize(Roles="admin,inventory-manager")]
    public class CategoryController : Controller
    {
        //
        // GET: /Category/

        public ActionResult List()
        {
            DAOFactory factory = new DAOFactory();
            //select the category to be displayed
            Category parent = null;
            if (Request["id"] != null)
            {
                parent = factory.CategoryDAO.GetById(Convert.ToInt64(Request["id"]));
            }
            else
            {
                parent = factory.CategoryDAO.GetRoot();
            }

            if (Request.RequestType.Equals("POST", StringComparison.OrdinalIgnoreCase))
            {
                //check if user want to remove a category
                if (Request["remove"] != null)
                {
                    long removeId = Convert.ToInt64(Request["removeId"]);
                    Category catToRemove = factory.CategoryDAO.GetById(removeId);
                    if (catToRemove != null)
                    {
                        parent.RemoveChild(catToRemove);
                        factory.CategoryDAO.Delete(catToRemove);
                        factory.CategoryDAO.Save(parent);
                    }
                }
                else //check if user want to add a category
                    if (Request["add"] != null)
                    {
                        Category catToAdd = new Category(Request["name"]);
                        parent.AddChild(catToAdd);
                        factory.CategoryDAO.Save(parent);
                    }
                    else //check if user want to rename current category
                        if (Request["rename"] != null)
                        {
                            parent.Name = Request["name"];
                            factory.CategoryDAO.Save(parent);
                        }
            }
            return View(parent);


        }

    }
}
